import React,{useState,useEffect,useRef} from 'react';
import {
    SafeAreaView,
    StyleSheet,
    ScrollView,
    View,
    Text,
    Image,
    StatusBar,
    TouchableOpacity,
    Platform,
    Share,
    DeviceEventEmitter, Linking,RefreshControl
} from 'react-native';
import colors from '../../utils/colors';
import screen from '../../utils/screen';
import ShadowBoxView from '../../widgets/ShadowBoxView';
import {AppModal} from '../../widgets/modal';
import RequestUtil from '../../utils/RequestUtil';
import Api from '../../utils/Api';
import Constants from '../../utils/Constants';
import {LGBtn,OLBtn,GrayBtn} from '../../widgets/buttons';
import Clipboard from '@react-native-community/clipboard';
import Images from '../../images/Images';
import {useStores} from '../../store';
import {observer} from 'mobx-react';
import {FontFamily, getffly} from '../../utils/common';
import MyProgress from '../../widgets/MyProgress';
import AppEvent from '../../utils/AppEvent';

const shadowOption = {
    radius:screen.PIXEL_40,
    color:'#000',
    border:2
}

export default  observer( ({navigation})=>{

    const {userStore} = useStores()
    const [data,setData] = useState(null)
    const [isRefreshing,setIsRefreshing] = useState(false)

    useEffect(()=>{
        getData()

        const emitter = DeviceEventEmitter.addListener(AppEvent.update_referralReward,()=>{
            getData()
        })
        return ()=>{
            emitter && emitter.remove()
        }
    },[])

    const getData = ()=>{

        AppModal.showLoading();
        setIsRefreshing(true)
        RequestUtil.get(Api.invitePage).then(res=>{

            let data = res.data
            console.log('team',data)
            setData(data)
            setIsRefreshing(false)
            AppModal.hideTip()
        },error=>{
            setIsRefreshing(false)
            AppModal.hideTip()
            AppModal.showError(error.msg)
            console.log('team error',error)
        })

    }

    const onReceive = ()=>{
        AppModal.showLoading();

        RequestUtil.post(Api.referralReceive,).then(res=>{
            console.log("user/referral/receive::" + res.data);
            AppModal.hideTip()
            AppModal.showSuccess("Reward received")
            getData()
        },error=>{
            AppModal.hideTip()
            AppModal.showError(error.msg)
            console.log('user/referral/receive',error)
        })
    }

    const renderShareBtn = (icon,title,onPress)=>{
        return (
            <TouchableOpacity
                style={{flexDirection:'row',alignItems:'center'}}
                onPress={onPress}
            >
                <Image source={icon}
                       resizeMode={'contain'}
                       style={{width:screen.PIXEL_40,height:screen.PIXEL_40}}
                />
                <Text style={{fontSize:13,color:'#000',marginLeft:3}}>{title}</Text>

            </TouchableOpacity>
        )
    }

    const renderCode = ()=>{
        const {share} = data
        return (
            <ShadowBoxView
                shadowOption={shadowOption}
            >
                <View style={{padding:screen.PIXEL_20,backgroundColor:'#fff',borderRadius:screen.PIXEL_40}}>
                    <Text style={{fontSize:13,color:'#000'}}>{Constants.team.referral_code}</Text>
                    <View style={{flexDirection:'row',justifyContent:'space-between',alignItems:'center'}}>
                        <Text style={{fontSize:24,color:'#FF7012'}}>{share.code}</Text>
                        <LGBtn
                            title={Constants.common.copy}
                            style={{width:screen.PIXEL_230,height:screen.PIXEL_80}}
                            onPress={()=>{
                                Clipboard.setString(share.code);
                                AppModal.showTip(Constants.team.code_copied)
                            }}
                        />
                    </View>


                </View>
            </ShadowBoxView>
        )
    }

    const renderLink = ()=>{
        const {share} = data
        return (
            <ShadowBoxView
                shadowOption={shadowOption}
            >
                <View style={{padding:screen.PIXEL_20,backgroundColor:'#fff',borderRadius:screen.PIXEL_40}}>
                    <Text style={{fontSize:13,color:'#000'}}>{Constants.team.referral_link}</Text>
                    <View style={{flexDirection:'row',justifyContent:'flex-end'}}>
                        <View style={{flex:1}}>
                            <Text style={{color:'#FF7012',fontSize:13}}>{share.link}</Text>
                        </View>

                        <LGBtn
                            title={Constants.common.copy}
                            style={{width:screen.PIXEL_230,height:screen.PIXEL_80}}
                            onPress={()=>{
                                Clipboard.setString(share.link);
                                AppModal.showTip(Constants.team.link_copied)
                            }}
                        />
                    </View>
                    <View style={{height:1,backgroundColor:'rgba(32,32,32,0.3)',marginTop:screen.PIXEL_30,marginBottom:screen.PIXEL_20}}/>
                    <View style={{flexDirection:'row',justifyContent:'space-between'}}>
                        {renderShareBtn(Images.email,'Email',()=>{

                            let str = '?subject=' + encodeURIComponent(userStore.userInfo.nickName + Constants.share.from) + '&body=' + encodeURIComponent(Constants.share.context + share.link)
                            Linking.openURL("mailto:" + str);
                        })}
                        {renderShareBtn(Images.whatsapp,'WhatsApp',()=>{
                            let str = encodeURIComponent(Constants.share.context + share.link)
                            Linking.openURL("https://wa.me/?text=" + str);
                        })}
                        {renderShareBtn(Images.more,'More',()=>{
                            let content = {
                                message:`${Constants.share.context} ${share.link}`,
                                title:`${userStore.userInfo.nickName} ${Constants.share.from}`
                            }
                            let options = Platform.OS === 'ios' ? {subject:Constants.share.subject} : {dialogTitle:Constants.share.subject}
                            Share.share(content,options)

                        })}
                    </View>

                </View>
            </ShadowBoxView>
        )
    }

    const renderTeamMember = ()=>{
        const {teamMember} = data
        return (
            <ShadowBoxView
                shadowOption={shadowOption}
            >
                <View style={{padding:screen.PIXEL_20,backgroundColor:'#fff',borderRadius:screen.PIXEL_40}}>
                    <Text style={{fontSize:13,color:'#000',fontFamily:getffly(FontFamily.bold)}}>{Constants.team.team_member}</Text>
                    <View style={{flexDirection:'row',justifyContent:'space-between',marginVertical:screen.PIXEL_20}}>
                        <View style={{alignItems:'center'}}>
                            <Text style={{fontSize:15,color:'#000'}}>{Constants.team.direct}</Text>
                            <Text style={{fontFamily:getffly(FontFamily.medium),color:'#FF7B14',fontSize:15,fontWeight:'500'}}>{teamMember.direct}</Text>
                        </View>

                        <View style={{alignItems:'center'}}>
                            <Text style={{fontSize:15,color:'#000'}}>{Constants.team.indirect}</Text>
                            <Text style={{fontFamily:getffly(FontFamily.medium),color:'#FF7B14',fontSize:15,fontWeight:'500'}}>{teamMember.second}</Text>
                        </View>

                        <View style={{alignItems:'center'}}>
                            <Text style={{fontSize:15,color:'#000'}}>{Constants.team.third_layer}</Text>
                            <Text style={{fontFamily:getffly(FontFamily.medium),color:'#FF7B14',fontSize:15,fontWeight:'500'}}>{teamMember.third}</Text>
                        </View>
                    </View>

                    <OLBtn
                        title={Constants.team.member_details}
                        style={{width:'100%',height:screen.PIXEL_80}}
                        onPress={()=>{
                            navigation.navigate('TeamMembers')
                        }}
                    />

                </View>


            </ShadowBoxView>
        )
    }

    const renderReferralReward = ()=>{
        const {referralReward} = data
        return (
            <ShadowBoxView
                shadowOption={shadowOption}
            >
                <View style={{padding:screen.PIXEL_20,backgroundColor:'#fff',borderRadius:screen.PIXEL_40}}>
                    <View style={{flexDirection:'row',justifyContent:'space-between'}}>
                        <Text style={{fontSize:13,color:'#000',fontFamily:getffly(FontFamily.bold)}}>{Constants.team.referral_reward}</Text>
                        <Text style={{fontSize:13,color:'#007AFF',textDecorationLine:'underline'}}
                              onPress={()=>{
                                  navigation.navigate('ReferralReward')
                              }}
                        >{Constants.team.member_details + ' >'}</Text>

                    </View>
                    <View style={{flexDirection:'row',justifyContent:'space-between',marginVertical:screen.PIXEL_20}}>
                        <View style={{alignItems:'center'}}>
                            <Text style={{fontSize:12,color:'#000'}}>{Constants.team.level_reached}</Text>
                            <Text style={{fontFamily:getffly(FontFamily.medium),color:'#FF7B14',fontSize:15,fontWeight:'500'}}>{referralReward.levelReached === 0 ? Constants.common.na : 'T'+referralReward.levelReached}</Text>
                        </View>

                        <View style={{alignItems:'center'}}>
                            <Text style={{fontSize:12,color:'#000'}}>{Constants.team.qualified_members}</Text>
                            <Text style={{fontFamily:getffly(FontFamily.medium),color:'#FF7B14',fontSize:15,fontWeight:'500'}}>{referralReward.qualifiedMembers}</Text>
                        </View>

                        <View style={{alignItems:'center'}}>
                            <Text style={{fontSize:12,color:'#000'}}>{Constants.team.total_rewards}</Text>
                            <Text style={{fontFamily:getffly(FontFamily.medium),color:'#FF7B14',fontSize:15,fontWeight:'500'}}>{Constants.appsymbol} {referralReward.totalRewards}</Text>
                        </View>
                    </View>

                    <Text style={{fontSize:15,color:'#000'}}>{Constants.team.next_level}</Text>

                    <View style={{flexDirection:'row',height:screen.PIXEL_80}}>
                        <View style={{flex:1,marginRight:screen.PIXEL_20,justifyContent:'space-between'}}>
                            <View style={{flexDirection:'row',justifyContent:'space-between'}}>
                                <Text style={{color:'#FF7B14',fontSize:13}}>{referralReward.levelNext.progress}/{referralReward.levelNext.total}
                                    <Text style={{color:'#000'}}> {Constants.team.qualified}</Text>
                                </Text>
                                <Text style={{color:'#FF7B14',fontSize:13}}>{Constants.appsymbol} {referralReward.levelNext.reward}</Text>
                            </View>

                            <MyProgress style={{width:screen.width - screen.PIXEL_320,height:10}} progress={referralReward.levelNext.progress/referralReward.levelNext.total}/>

                        </View>

                        {
                            referralReward.levelNext.progress === referralReward.levelNext.total ? (
                                <LGBtn
                                    title={Constants.team.receive}
                                    style={{width:screen.PIXEL_180,height:screen.PIXEL_80}}
                                    onPress={()=>{
                                        onReceive()
                                    }}
                                />
                            ):(
                                <GrayBtn
                                    title={Constants.team.receive}
                                    style={{width:screen.PIXEL_180,height:screen.PIXEL_80}}
                                />
                            )
                        }

                    </View>

                </View>


            </ShadowBoxView>
        )
    }

    const renderTeamReward = ()=>{
        const {orderReward} = data
        return (
            <ShadowBoxView
                shadowOption={shadowOption}
            >
                <View style={{padding:screen.PIXEL_20,backgroundColor:'#fff',borderRadius:screen.PIXEL_40}}>
                    <Text style={{fontSize:13,color:'#000',fontFamily:getffly(FontFamily.bold)}}>{Constants.team.team_reward}</Text>

                    <View style={{flexDirection:'row',justifyContent:'space-between',marginVertical:screen.PIXEL_20}}>
                        <View style={{alignItems:'center'}}>
                            <Text style={{fontSize:15,color:'#000'}}>{Constants.team.today}</Text>
                            <Text style={{fontFamily:getffly(FontFamily.medium),color:'#FF7B14',fontSize:15,fontWeight:'500'}}>{orderReward.today}</Text>
                        </View>

                        <View style={{alignItems:'center'}}>
                            <Text style={{fontSize:15,color:'#000'}}>{Constants.team.week}</Text>
                            <Text style={{fontFamily:getffly(FontFamily.medium),color:'#FF7B14',fontSize:15,fontWeight:'500'}}>{orderReward.week}</Text>
                        </View>

                        <View style={{alignItems:'center'}}>
                            <Text style={{fontSize:15,color:'#000'}}>{Constants.team.total}</Text>
                            <Text style={{fontFamily:getffly(FontFamily.medium),color:'#FF7B14',fontSize:15,fontWeight:'500'}}>{orderReward.total}</Text>
                        </View>
                    </View>

                    {
                        orderReward.recent.map((item,index)=>{
                            return (
                                <View style={{flexDirection:'row',justifyContent:'space-between'}}
                                      key={index}
                                >
                                    <Text style={{color:'#000',fontSize:15}}>{item.type}</Text>
                                    <Text style={{color:'#3F8A83',fontSize:15}}>{item.name}</Text>
                                    <Text style={{color:'#FF7B14',fontSize:15}}>+{item.amount}</Text>
                                </View>
                            )
                        })
                    }

                    <LGBtn
                        title={Constants.team.view_records}
                        style={{width:'100%',height:screen.PIXEL_80,marginTop:screen.PIXEL_50}}
                        onPress={()=>{
                            navigation.navigate('TeamReward')
                        }}
                    />

                </View>


            </ShadowBoxView>
        )
    }

    return (
        <View style={styles.container}>
            <View style={styles.content}>
                <TouchableOpacity
                    style={{flexDirection:'row',alignItems:'center',alignSelf:'flex-end',paddingRight:screen.PIXEL_30,
                        paddingBottom:screen.PIXEL_20
                    }}
                    onPress={()=>{
                        navigation.navigate('InviteRules')
                    }}
                >
                    <Text style={{fontSize:14,color:'#377C74'}}>{Constants.team.rules}</Text>
                    <Image source={Images.right}
                           resizeMode={'contain'}
                           style={{width:screen.PIXEL_20,height:screen.PIXEL_20}}/>

                </TouchableOpacity>
                {
                    data && (
                        <ScrollView
                            style={{flex: 1, marginBottom: 20}}
                            contentContainerStyle={{
                                paddingBottom: screen.PIXEL_40,
                                paddingTop:screen.PIXEL_20,
                                paddingHorizontal: screen.PIXEL_40,
                            }}
                            refreshControl = {
                                <RefreshControl
                                    refreshing={ isRefreshing }
                                    onRefresh = {() => getData()}
                                />
                            }
                        >
                            {renderCode()}
                            <View style={{height:screen.PIXEL_30}}/>
                            {renderLink()}
                            <View style={{height:screen.PIXEL_30}}/>
                            {renderTeamMember()}
                            <View style={{height:screen.PIXEL_30}}/>
                            {renderReferralReward()}
                            <View style={{height:screen.PIXEL_30}}/>
                            {renderTeamReward()}
                        </ScrollView>
                    )
                }

            </View>
        </View>
    )
})




const styles = StyleSheet.create({
    container: {
        flex:1,
        backgroundColor:colors.tabBgColor
    },
    content:{
        flex:1,backgroundColor: '#fff',
        borderBottomLeftRadius:screen.PIXEL_110,
        borderBottomRightRadius:screen.PIXEL_110,
        paddingTop:screen.statusBarHeight
    }
})
